<template>
  <a-layout class="layout">

    <a-layout-header  class="searchHeader" style="background-color: white; box-shadow: -10px 10px 10px -10px rgba(0, 0, 0, 0.3); height: 60px" >
      <SearchHeader  :title='pageTitle'/>
    </a-layout-header>

    <!-- 导航栏-->
    <div :bordered="false" :style="{backgroundColor: '#f2f2f2',height: '100%'}">
      <div :bordered="false" :style="{backgroundColor: '#f2f2f2',height: '100%'}">
        <main class="km-page ant-layout-content">
          <div style="margin: 20px 0px;">
            <nav  class="ant-breadcrumb">
              <a><span @click="jumpManage('defaultDocSearch')">首页</span></a>
              <span class="ant-breadcrumb-separator">/</span>
              <span>上传知识文档</span>
            </nav>
          </div>

          <!-- 知识属性-->
          <div style="background: white;border-radius: 10px;">
            <a-col style="background-color: #081C42">
              <h3 style="color: white;margin-left: 10px;padding:5px">
                <b>知识属性</b>
              </h3>
            </a-col>
            <a-form-model  ref="form" :model="model" :rules="validatorRules" slot="detail">
              <a-row style="background: white;min-height: 900px">

             <div class="ant-row" style="margin-left: -12px; margin-right: -12px;margin-top: 10px;">
               <a-col :span="11"  style="padding-left: 12px;padding-right: 12px;height: 55px">
                 <div class="ant-row">
              <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title">
                <a-input placeholder="请输入标题" v-model="model.title"></a-input>
              </a-form-model-item></div>
               </a-col>

               <a-col :span="11"  style="padding-left: 12px;padding-right: 12px;height: 55px">
                 <div class="ant-row">
                 <a-form-model-item label="知识分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
                   <j-dict-select-tag type="list" placeholder="请选择知识分类" v-model="model.category"
                   dictCode="km_dict_category"></j-dict-select-tag>
                 </a-form-model-item></div>
               </a-col>
             </div>

                <div class="ant-row" style="margin-left: -12px; margin-right: -12px;">

                  <a-col :span="11"  style="padding-left: 12px;padding-right: 12px;height: 55px">
                    <div class="ant-row">
                      <a-form-model-item label="归属部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depId">
                        <j-select-depart v-model="model.depId" :multi="false"></j-select-depart>
                      </a-form-model-item>
                       </div>
                  </a-col>

                  <a-col :span="11"  style="padding-left: 12px;padding-right: 12px;height: 55px">
                    <div class="ant-row">
                      <a-form-model-item label="专题分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
                        <a-textarea @click="showModel(model)" v-model="model.topicIds_dictText"
                                    placeholder="请点击选择专题" readOnly  :auto-size="{ minRows: 1, maxRows: 3 }">
                        </a-textarea>
                      </a-form-model-item>
                    </div>
                  </a-col>
                </div>

                <div class="ant-row" style="margin-left: -12px; margin-right: -12px;">
                  <a-col :span="11"  style="padding-left: 12px;padding-right: 12px;height: 55px">
                    <div class="ant-row">
                      <a-form-model-item label="关键字" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="keywords">
                        <a-textarea v-model="model.keywords" placeholder="请输入关键字"
                                    :auto-size="{ minRows: 1, maxRows: 3 }"></a-textarea>
                      </a-form-model-item>
                    </div>
                  </a-col>
                </div>

                <div class="ant-col">
                  <span  class="title-txt content-tittle-txt" style="margin-right: 20px;">知识可见性</span>
                </div>
                <div class="ant-row" style="margin-left: -12px; margin-right: -12px;">
                  <a-col :span="7"  style="padding-left: 8px;padding-right: 12px;height: 55px">
                    <div class="ant-row">
                      <a-form-model-item label="公开方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="publicRemark">
                        <j-dict-select-tag type="list" placeholder="请选择公开方式" v-model="model.publicRemark"
                                           dictCode="km_dict_public_remark"></j-dict-select-tag>
                      </a-form-model-item>
                    </div>
                  </a-col>

                  <a-col :span="7"  style="padding-left: 8px;padding-right: 12px;height: 55px">
                    <div class="ant-row">
                      <a-form-model-item label="知识库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="knowledgeBase">
                        <a-select  v-model="model.knowledgeBase"  class="my-select-dropdown"
                                   filterable
                                   allowClear
                                   default-first-option
                                   placeholder="请选择知识库"
                        >
                          <a-select-option
                            v-for="item in data2"
                            :key="item.id"
                            :value="item.roleName">
                            {{ item.roleName }}
                          </a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </div>
                  </a-col>

                  <a-col :span="7"  style="padding-left: 8px;padding-right: 12px;height: 55px">
                    <div class="ant-row">
                      <a-form-model-item label="涉及业务" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessTypes">
                        <j-multi-select-tag type="list_multi" v-model="model.businessTypes" :trigger-change="true"
                                            placeholder="请选择涉及业务" dictCode="km_dict_business"></j-multi-select-tag>
                      </a-form-model-item>
                    </div>
                  </a-col>
                </div>


                <div class="ant-col">
                  <span  class="title-txt content-tittle-txt" style="margin-right: 20px;">上传附件</span>
                </div>
                <div class="ant-row" style="margin-left: 35px;width: 600px">
                  <el-upload
                    name="file"
                    ref="upload"
                    :action="urls"
                    :headers="headers"
                    :multiple="true"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :on-change="beforeUpload"
                    :file-list="fileList"
                    :auto-upload="false"
                    :show-upload-list="true"
                  >
                  <el-button slot="trigger" size="small">
                    上传<i class="el-icon-upload el-icon--right">
                  </i></el-button>
                  </el-upload>
                </div>

                <div class="ant-col">
                  <span  class="title-txt content-tittle-txt" style="margin-right: 20px;margin-top: 20px;">内容摘要</span>
                </div>
                <div class="ant-row" style="margin-left: -12px; margin-right: -12px;">
                  <a-col :span="22"  style="padding-left: 12px;padding-right: 12px;height: 50px">
                    <div class="ant-row" style="margin-left: 20px;">
                      <template>
                        <quill-editor style="height: 400px;"  v-model="model.remark"></quill-editor></template>
                    </div>
                  </a-col>
                </div>

                  <span  class="tittle-txt" style="width: 2px;height: 430px"></span>

                <div class="ant-row" style="margin-left: -12px; margin-right: -12px;">
                <div class="km-bottom-view header-shadow">
                <div class="km-page"  style="text-align: right;">
                  <a-form-model-item>
                    <el-button  class="ant-btn ant-btn-primary"
                               type="success"  style="width: 100px;height: 40px;font-size: 16px;" @click="handleSubmit(model)">提交</el-button>
                  </a-form-model-item>
                 </div>
                </div>
                </div>
              </a-row>
            </a-form-model>
            <subject-modal ref="modalForm" @ok="modalFormOk"></subject-modal>
            </div>
        </main>
      </div>
    </div>
    <a-layout-footer style="padding: 0">
      <global-footer/>
    </a-layout-footer>
  </a-layout>
</template>

<script>
  import SearchHeader from '../Common/SearchHeader';
  import GlobalFooter from '@/components/page/GlobalFooter';
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import {getAction,httpAction} from '@/api/manage'
  import SubjectModal from '../filemanagement/modules/SubjectModal'
  import Vue from "vue";
  import VueQuillEditor from 'vue-quill-editor';
  import 'quill/dist/quill.core.css'; // 引入样式
  import 'quill/dist/quill.snow.css'; // 引入样式
  import 'quill/dist/quill.bubble.css';
  Vue.use(VueQuillEditor)


    export default {
        name: "CreateDocuments",
      components: {SearchHeader,GlobalFooter,SubjectModal},
      data() {
        return {
          model: {
            id:"",
            publicRemark:1,
          },
          data2: [],
          fileList:[],
          UploadFailed:"",
          urls: window._CONFIG['domianURL']+"/KM/kmDoc/ManualUploadDoc",
          headers: {
            authorization: 'authorization-text',
            'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)
          },
          validatorRules: {
            title: [{required: true, message: '标题不能为空!'}],
          },
          labelCol: {
            xs: {span: 24},
            sm: {span: 6},
          },
          wrapperCol: {
            xs: {span: 24},
            sm: {span: 18},
          },
          businessTypes: '',
          url: {
            list2: '/sys/knowledgebase/list',
             edit: '/KM/kmDoc/editFile',
            insertDoc: '/KM/kmDoc/insertDoc',
          },
        }
      },
      created() {
        this.loadData2();
      },
      methods: {
        loadData2() {
          console.log("========this.url.list2========" + JSON.stringify(this.url.list2))
          let params = {}
          getAction(this.url.list2, params).then((res) => {
            console.log("========res========" + JSON.stringify(res))
            if (res.success) {
              this.data2 = res.result.records
            }
          })
        },

        handleSubmit(model) {
          // 触发表单验证
          this.$refs.form.validate(valid => {
            console.log("=====valid======" + JSON.stringify(valid))
            if (valid) {
              console.log("=====this.model========" + JSON.stringify(this.model))
              console.log("=====文件长度========" + JSON.stringify(this.fileList.length))

              if (this.fileList.length > 0) {
              if(this.UploadFailed==""){
                this.$refs.upload.submit();
              }else {
                this.$message.error(`${this.UploadFailed}`);
               }
              }else {
                if (model.businessTypes == ""||model.businessTypes==null||model.businessTypes==undefined) {
                  console.log("不操作businessTypes");
                } else {
                  var businessTypesArr = model.businessTypes.split(',');
                  var businessTypesArrConst = this.businessTypes.split(',');
                  model.addBusinessTypeList = [];
                  model.removeBusinessTypeList = [];
                  for (let i = 0; i < businessTypesArr.length; i++) {
                    for (let j = 0; j < businessTypesArrConst.length; j++) {
                      if (businessTypesArr[i] === businessTypesArrConst[j]) {
                        delete businessTypesArr[i];
                        delete businessTypesArrConst[j];
                      }
                    }
                  }
                  for (let i = 0; i < businessTypesArr.length; i++) {
                    if (typeof (businessTypesArr[i]) != "undefined") {
                      model.addBusinessTypeList.push(businessTypesArr[i]);
                    }
                  }
                  for (let i = 0; i < businessTypesArrConst.length; i++) {
                    if (typeof (businessTypesArrConst[i]) != "undefined") {
                      model.removeBusinessTypeList.push(businessTypesArrConst[i]);
                    }
                  }
                }
                model.previewfileType="default"
                model.source=1
                console.log("=====model======" + JSON.stringify(model))
                httpAction(this.url.insertDoc, model, 'post').then((res) => {
                  console.log("=====日志======" + JSON.stringify(res))
                  if (res.success) {
                    this.$message.success(`上传成功`);
                    // this.$router.push({ name: 'defaultDocSearch' });
                 this.jumpManage('defaultDocSearch');
                  } else {
                    this.$message.warning(res.message);
                  }
                })
              }

            }
          })
        },

        beforeUpload(file, fileList) {
          console.log("=====fileList======" + JSON.stringify(fileList))
          // 清空已有的文件列表
          // this.$refs.upload.clearFiles();
          // 添加新文件到文件列表
          // this.fileList = [file];
          this.fileList = fileList;
        },

        handleSuccess(response, file, fileList) {
          console.log("=====文件名称=======" + JSON.stringify(file.name))
          // 文件上传成功时的回调
          console.log('文件上传成功', response);
          // 可以在这里更新UI，提示上传成功等
          if(response.code===200){
            this.UploadFailed="";
            this.model.id=response.result
            console.log("=====上传内容=====" + JSON.stringify(this.model))
            if(this.model.id!=""){
              if (this.model.businessTypes == ""||this.model.businessTypes==null||this.model.businessTypes==undefined) {
                console.log("不操作businessTypes");
              } else {
                var businessTypesArr = this.model.businessTypes.split(',');
                var businessTypesArrConst = this.businessTypes.split(',');
                this.model.addBusinessTypeList = [];
                this.model.removeBusinessTypeList = [];
                for (let i = 0; i < businessTypesArr.length; i++) {
                  for (let j = 0; j < businessTypesArrConst.length; j++) {
                    if (businessTypesArr[i] === businessTypesArrConst[j]) {
                      delete businessTypesArr[i];
                      delete businessTypesArrConst[j];
                    }
                  }
                }
                for (let i = 0; i < businessTypesArr.length; i++) {
                  if (typeof (businessTypesArr[i]) != "undefined") {
                    this.model.addBusinessTypeList.push(businessTypesArr[i]);
                  }
                }
                for (let i = 0; i < businessTypesArrConst.length; i++) {
                  if (typeof (businessTypesArrConst[i]) != "undefined") {
                    this.model.removeBusinessTypeList.push(businessTypesArrConst[i]);
                  }
                }
              }
              this.model.previewfileType="default"
              this.model.source=1
              console.log("=====this.model======" + JSON.stringify(this.model))
              httpAction(this.url.edit,this.model,'put').then((res) => {
                if (res.success) {
                  this.$message.success(`文件上传成功`);
                  // this.$router.push({ name: 'defaultDocSearch' });
                  this.jumpManage('defaultDocSearch');
                } else {
                  this.$message.error(`文件上传失败`);
                  this.$set(file, 'status', 'failed');
                }
              })
            }
          }else if (response.code === 500) {
            this.$message.error(`${response.message}`);
            this.$set(file, 'status', 'failed');
            this.UploadFailed=response.message
          }
        },

        handleError(error, file, fileList) {
          // 文件上传失败时的回调
          console.error('文件上传失败', error);
          // 可以在这里更新UI，提示上传失败等
          this.$message.error(`${file.name} 文件上传失败`);
        },


        // 用来控制上传控件列表的显示
        handleChange(info) {
          console.log("=====fileList.length========" + JSON.stringify(fileList.length))
          // if (fileList.length > 1) {
          //   // 如果有多个文件，移除第一个文件
          //   this.fileList.shift();
          // }
          var boolFilelistAdd=true;
          this.fileList.forEach((item,index)=>{
            console.log("=====item.uid========" + JSON.stringify(item.uid))
            console.log("=====info.file.uid========" + JSON.stringify(info.file.uid))
            if(item.uid==info.file.uid){
              boolFilelistAdd=false;
            }
          });
          if(boolFilelistAdd){
            this.fileList.push(info.file)
          }
          console.log("=====文件上传状态========" + JSON.stringify(info.file.status))
          if(info.file.status !== 'uploading'){
            if (info.file.status === 'done') {
              if(info.file.response.code===200){
                console.log("=====后台方法值========" + JSON.stringify(info.file.response))
                console.log("=====文件上传成功后model修改====" + JSON.stringify(this.model))
                this.$message.success(`${info.file.name} 文件上传成功`);
              }else{
                this.fileList.forEach((item,index)=>{
                  if(item.uid===info.file.uid){
                    this.fileList[index].status='error';
                    this.fileList[index].response=info.file.response.message;
                  }
                });
                this.$message.error(`${info.file.name} 文件上传失败${info.file.response.message}`);

              }
            } else if (info.file.status === 'error') {

              this.fileList.forEach((item,index)=>{
                if(item.uid===info.file.uid){
                  this.fileList[index].status='error';
                }
              });
              this.$message.error(`${info.file.name} 文件上传失败`);
            }
          }
        },

        //返回方法
        jumpManage(defaultDocSearch) {
          const route = this.$router.resolve({ name: defaultDocSearch });
          // 更新 window.location 来触发页面的重新加载
          window.location.href = route.href;
        },

        //  显示专题
        showModel(model) {
          console.log("=====model.topicIds_dictText======" + JSON.stringify(model.topicIds_dictText))
          this.$refs.modalForm.edit(model, 0);
          this.$refs.modalForm.title = "选择专题"
          // // 确保更新是响应式的
            this.$nextTick(() => {
              this.$set(model, 'topicIds_dictText', model.topicIds_dictText);
            });
        },

      },

    }
</script>

<style scoped>

  .ant-breadcrumb {
    font-size: 14px; /* 根据您的设计调整字体大小 */
    color: rgba(0, 0, 0, 0.65); /* 默认面包屑颜色 */
  }

  /* 首页链接样式，设置透明度 */
  .ant-breadcrumb > span:first-child > a {
    color: transparent; /* 首页文字透明 */
    text-shadow: none; /* 如果有文本阴影，也将其移除 */
  }

  /* 首页链接中span的样式，设置透明度 */
  .ant-breadcrumb > span:first-child > a > span {
    color: transparent; /* 首页文字透明 */
  }

  /* 上传知识文档文字样式，设置为黑色 */
  .ant-breadcrumb > span:nth-child(3) {
    color: black; /* 文字颜色设置为黑色 */
  }

  /* 面包屑分隔符样式，可以根据需要调整 */
  .ant-breadcrumb-separator {
    color: rgba(0, 0, 0, 0.65); /* 分隔符颜色 */
  }

  .ant-breadcrumb > span:first-child > a:hover {
    color: rgba(0, 0, 0, 0.85); /* 鼠标悬停时首页链接颜色变为半透明 */
  }

  .ant-layout, .ant-layout * {
    box-sizing: border-box;
  }

  .ant-layout-content {
    -webkit-box-flex: 1;
    -ms-flex: auto;
    flex: auto;
    min-height: 0;
  }

  @media (min-width: 1200px) {
    .km-page {
      width: 80%;
      margin: auto;
    }
  }

  .content-tittle-txt {
    margin-top: 12px;
    margin-bottom: 12px;
    color: #000c17;
    border-left: 5px solid #0a84ff;
    font-size: 16px;
    display: inline-block;
    font-weight: bolder;
    padding-left: 15px;
    margin-right: 5px;
  }

  .tittle-txt {
    margin-top: 12px;
    margin-bottom: 12px;
    border-left: 5px solid #ffffff;
    font-size: 16px;
    display: inline-block;
    font-weight: bolder;
    padding-left: 15px;
    margin-right: 5px;
  }

  .title-txt {
    color: #303133;
    font-size: 15px;
    font-weight: bolder;
    margin-left: 20px;
  }

  .ant-row {
    position: relative;
    height: auto;
    margin-right: 0;
    margin-left: 0;
    zoom: 1;
    display: block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }

  .ant-col {
    position: relative;
    min-height: 1px;
  }

  .km-bottom-view {
    position: fixed;
    bottom: 0;
    left: 0;
    text-align: center;
    background: #fff;
    width: 100%;
    padding: 10px 0;
    z-index: 1000; /* 一个示例值，根据需要调整 */
  }

  .header-shadow {
    box-shadow: 0 3px 10px 1px #dedede;
    -webkit-box-shadow: 0 3px 10px 1px #dedede;
    -moz-box-shadow: 0 3px 10px 1px #dedede;
    height: 55px;
  }

  .ant-btn-primary {
    color: #fff;
    background-color: #081C42;
    border-color: #081C42;
  }

  .ant-btn {
    color: #fff;
  }

  :deep(.el-upload__input) {
    display: none !important;
  }

  /deep/.ant-form input[type=file] {
    display: none !important;
  }

  /deep/.el-upload-list__item .fail {
    color: red;
  }
</style>